package org.demo.jms;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.jms.Connection;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 
 * @author  
 * @date    2010-12-30
 * @file    org.demo.jms.QueueSender.java
 */
public class QueueSender {

	private static final String url = "tcp://localhost:61616";
	private static final String queue = "plan";
	
	private Connection conn = null;
	private Session session = null;
	
	/**
	 * @param args
	 */
	public static void main(String[] args)throws Exception {
		
		QueueSender sender = new QueueSender();
		sender.init();
		
		TextMessage msg = sender.session.createTextMessage();
		msg.setText(sender.getFileContent());
		
		Destination destination = sender.session.createQueue(queue);
		MessageProducer producer = sender.session.createProducer(destination);
		producer.send(msg);
		
		sender.close();
		
		System.out.println("-- jms message send. --");
	}
	/**
	 * 构造函数
	 */
	public QueueSender(){
		
	} 
	/**
	 * 初始化 jms
	 * @return
	 * @throws JMSException
	 */
	public void init() throws JMSException{
		
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("", "", url);
		conn = factory.createConnection();
		conn.start();
		
		session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
	}
	/**
	 * 断开 jms 连接
	 */
	public void close(){
		try {
			session.close();
			conn.close();
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	/**
	 * 获取文件内容
	 * @return
	 */
	private String getFileContent(){
		StringBuilder sb = new StringBuilder();
		
		InputStream in = this.getClass().getResourceAsStream("data.xml");
		try {
			InputStreamReader isr = new InputStreamReader(in, "utf-8");
			BufferedReader buf = new BufferedReader(isr);
			String data = null;
			while ((data = buf.readLine()) != null){
				sb.append(data).append("\r\n");
			}
			buf.close();
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			try {in.close();} catch(Exception e){}
		}
		
		return sb.toString();
	}
}
